import React from 'react';
import { Select, Button, Table, Space, Switch, message, Form, Input, Modal } from 'antd';
import { useEffect, useState } from 'react';
import { request } from 'umi'

const dishList = () => {

    // 编辑
    const [propObj, setPropObj] = useState({});
    const [propId, setPropId] = useState({});
    // 编辑功能的弹出框
    const EditForm = ({ visible, onCreate, onCancel }) => {
        const [form] = Form.useForm();
        return (
            <Modal
                visible={visible}
                title="编辑"
                okText="确定"
                cancelText="取消"
                onCancel={onCancel}
                onOk={() => {
                    form.validateFields().then((values) => {
                        form.resetFields();
                        onCreate(values);
                    })
                        .catch((info) => {
                            console.log('Validate Failed:', info);
                        });
                }}
            >
                <Form
                    form={form}
                    layout="vertical"
                    name="form_in_modal"
                    initialValues={{
                        modifier: 'public',
                        index: propObj.index,
                        name: propObj.name,
                        price: propObj.price,
                        status: propObj.status,
                        class: propId
                    }}
                >

                    <Form.Item name="index" label="序号"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item name="name" label="名称"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input type="textarea" />
                    </Form.Item>

                    <Form.Item
                        name="price"
                        label="价格"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        name="class"
                        label="分类"
                        rules={[{ required: true, message: '选择分类!' }]}
                    >
                        <Select placeholder="选择分类">
                            {series.map((item, index) => {
                                return (
                                    <Option key={index} value={item._id} serie={item._id}>{item.name}</Option>
                                )
                            })}
                        </Select>
                    </Form.Item>

                    <Form.Item name="status" label="状态" valuePropName="checked">
                        <Switch />
                    </Form.Item>

                </Form>
            </Modal>
        );
    };
    
    // 编辑功能
    const [visible_edit, setVisible_edit] = useState(false);
    const handleEdit = (id) => {
        request("http://www.young1024.com:1717/v1/dish/list").then(
            (res) => {
                console.log(res);
                let obj = res.data.find(item => item._id === id);
                obj["id"] = id;
                console.log(obj);
                setPropObj(obj)
                if (obj.serie) {
                    setPropId(obj.serie._id)
                }else{
                    setPropId("")
                }
                setVisible_edit(true)
            },
            (err) => { console.log(err); }
        )
    }

    //创建编辑表单功能
    const onCreate_edit = (values) => {
        console.log('Received values of form: ', values);
        const param = new URLSearchParams;
        param.append("id", propObj.id)
        param.append("index", values.index)
        param.append("name", values.name)
        param.append("status", values.status)
        param.append("serie", values.class)
        request("http://www.young1024.com:1717/v1/dish/update", { data: param }).then(
            (res) => {
                console.log(res);
                if (res.status === "success") {
                    getData();
                    message.info('添加成功');
                    setVisible_edit(false);
                }
            },
            (err) => { console.log(err); }
        )
    };







    const { Option } = Select;
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            render: text => <a>{text}</a>,
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: status => <Switch size="small" defaultChecked={status} />
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    <Button type="primary" onClick={() => { handleEdit(text._id) }}>
                        编辑
                    </Button>
                    <Button type="primary" danger onClick={() => { handleDelete(text._id) }}>
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    const [list, setList] = useState([])
    const getData = () => {
        request("http://www.young1024.com:1717/v1/dish/list").then(
            (res) => {
                setList(res.data)
            },
            (err) => { console.log("失败", err); }
        )
    }

    const [series, setSeries] = useState([])
    const getSeries = () => {
        request("http://www.young1024.com:1717/v1/serie/list").then(
            (res) => {
                setSeries(res.data)
            },
            (err) => { console.log("失败", err); }
        )
    }

    useEffect(() => {
        getData();
        getSeries()
    }, [])

    const handleDelete = (id) => {
        let param = new URLSearchParams;
        param.append("id", id);
        request("http://www.young1024.com:1717/v1/dish/del", { data: param }).then(
            (res) => {
                if (res.status === "success") {
                    getData()
                    message.info('删除成功');
                }
            },
            (err) => {
                console.log(err);
            }
        )
    }

    return (
        <div style={{ padding: "20px", height: "100%" }}>
            <div style={{ padding: "20px", background: "white", minHeight: "800px" }}>
                <h2>菜品列表</h2>
                <div>
                    分类：
                    <Select defaultValue="lucy" style={{ width: 120 }} allowClear>
                        <Option value="lucy">Lucy</Option>
                    </Select>
                    <Button type="primary" htmlType="submit" style={{ marginLeft: "20px" }}>
                        搜索
                    </Button>
                </div>
                <div>
                    <Table columns={columns} dataSource={list} rowKey={record => record._id} />
                </div>
            </div>
            <EditForm
                visible={visible_edit}
                onCreate={onCreate_edit}
                onCancel={() => {
                    setVisible_edit(false);
                }}
            />
        </div>
    );
}

export default dishList;
